﻿// SerialPortInstance
// 
// Class representing a serial port instance
// 
// FLMScan - Featured by FabLab Munich

using System;
using FLMScan.Exception;

namespace FLMScan.Serial
{
    class SerialPortWrapper : IDisposable
    {        
        private ISerialPort serialPort;
        private bool isDisposed = false;        

        public SerialPortWrapper(ISerialPort serialPort)
        {
            try
            {
                this.serialPort = serialPort;
                serialPort.Open();
            }
            catch (InvalidOperationException)
            {
                // do nothing if port was already open
            }
            catch (System.Exception ex)
            {
                if (!ExceptionHelper.IsUnhandledException(ex))
                    throw new SerialPortException("Serial port initialization failed! Exception caught.", ex);
            }
        }        

        public void Write(char[] buffer, int offset, int count)
        {
            try
            {
                serialPort.Write(buffer, offset, count);
            }
            catch (System.Exception ex)
            {                
                if (!ExceptionHelper.IsUnhandledException(ex))
                    throw new SerialPortException("Writing to serial port failed! Exception caught.", ex);
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        private void Dispose(bool isDisposing)
        {
            if (isDisposed)
                return;

            if (isDisposing)
            {
                isDisposed = true;
                serialPort.Close();
            }
        }   
    }
}
